package me.xue.communityhealth.admin.controller;

import com.github.pagehelper.Page;
import me.xue.communityhealth.model.Staff;
import me.xue.communityhealth.service.DepartmentService;
import me.xue.communityhealth.service.PostService;
import me.xue.communityhealth.service.StaffService;
import me.xue.communityhealth.util.ApplicationUtil;
import me.xue.communityhealth.util.FileUtil;
import me.xue.communityhealth.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Controller
@lombok.extern.log4j.Log4j2
public class StaffController {

    private final StaffService staffService;

    private final DepartmentService departmentService;

    private final PostService postService;

    @Autowired
    public StaffController(StaffService staffService, DepartmentService departmentService, PostService postService) {
        this.staffService = staffService;
        this.departmentService = departmentService;
        this.postService = postService;
    }

    @GetMapping("/staffs")
    public String staffs(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                         @ModelAttribute("message") String message,
                         Model model) {
        Page<Staff> staffPage = staffService.pagedPatients(page);
        model.addAttribute("staffs", staffPage.getResult());
        model.addAttribute("pageInfo", staffPage.toPageInfo());
        return "staffs";
    }

    @GetMapping("/staff/add")
    public String addStaffPage(Model model) {
        model.addAttribute("staff", new Staff());
        addParams(model);
        return "staff_edit";
    }

    @PostMapping("/staff")
    public String addStaff(@Valid Staff staff, BindingResult bindingResult,
                           @RequestParam(value = "portraitFile", required = false, defaultValue = "null") MultipartFile multipartFile,
                           RedirectAttributes redirectAttributes,
                           Model model) {
        addParams(model);

        if (bindingResult.hasErrors()) {
            log.error("添加员工失败: {}", bindingResult.getAllErrors());
            return "staff_edit";
        }
        staff.setPortrait(staffService.savePortrait(multipartFile, getName(staff.getName())));
        int row = staffService.save(staff);
        if (row == 1) {
            redirectAttributes.addFlashAttribute("message", "保存成功");
            return "redirect:/staffs";
        }
        return "staff_edit";
    }

    @GetMapping("/staff/{id:\\d+}/edit")
    public String editStaffPage(@PathVariable("id") int id, Model model) {
        Staff staff = staffService.findStaff(id);
        model.addAttribute("staff", staff);
        addParams(model);
        return "staff_edit";
    }

    @PutMapping("/staff")
    public String updateStaff(@Valid Staff staff, BindingResult bindingResult,
                              @RequestParam(value = "portraitFile", required = false, defaultValue = "null") MultipartFile multipartFile,
                              RedirectAttributes redirectAttributes,
                              Model model) {
        addParams(model);

        if (bindingResult.hasErrors()) {
            log.error("更新员工失败: {}", bindingResult.getAllErrors());
            return "staff_edit";
        }

        if (multipartFile != null && !multipartFile.isEmpty()) {
            log.info("multipart file name + " + multipartFile.getOriginalFilename());
            staff.setPortrait(FileUtil.saveMultipartFile(multipartFile, ApplicationUtil.getPortraitPath().getAbsolutePath(), staff.getPortrait()));
        }

        int row = staffService.update(staff);
        if (row == 1) {
            redirectAttributes.addFlashAttribute("message", "修改成功");
            return "redirect:/staffs";
        }

        return "staff_edit";
    }

    @DeleteMapping("/staff/{id:\\d+}")
    @ResponseBody
    public String deleteStaff(@PathVariable("id") int id) {
        Staff staff = staffService.findStaff(id);
        int row = staffService.delete(id);
        if (row == 1) {
            staffService.deletePortrait(staff.getPortrait());
            return "success";
        }
        return "删除失败";
    }

    private void addParams(Model model) {
        //部门
        List<String> departments = departmentService.findAll();
        model.addAttribute("departments", departments);
        //职务
        List<String> posts = postService.findAll();
        model.addAttribute("posts", posts);
    }

    private String getName(String orig) {
        return Md5Util.getHashKey(orig + new Date().toString());
    }

}
